<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 好店
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinStore;
use app\allwin\model\AllwinStoreChain;
use app\allwin\model\Coupon;
use app\allwin\model\CouponUser;
use app\allwin\model\Order;
use app\allwin\model\MchId;
use app\allwin\model\AllwinConfig;
use app\common\facade\WechatPay;
use app\common\model\SystemMemberForm;


class Payment extends Base{

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }

    /**
     * 买单付款
     * @param integer 读取ID
     * @return json
     */
    public function index(){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['code_id']  = $this->request->param('code_id/s',0);
        $param['signkey']  = $this->request->param('signkey');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        if($param['code_id']){
            $where['code_id'] = $param['code_id'];
        }else{
            $where['id']      = $param['store_id'];
        }
        $where['member_miniapp_id'] = $this->miniapp_id;
        $where['is_lock']           = 0;
        $store = AllwinStore::where($where)->field('id,name,tips,quan_id')->find();
        if(empty($store)){
            if($param['code_id']){
                $chain_where['member_miniapp_id'] = $this->miniapp_id;
                $chain_where['code_id']           = $param['code_id'];
                $chain = AllwinStoreChain::with(['store' => function($query) {
                    $query->field('id,name,tips,quan_id');
                }])->where($chain_where)->find();
                if(empty($chain->store)){
                    return enjson(301,'未找到付款好店1',['url' =>'/pages/index']);
                }
                $store = $chain->store;
            }else{
                return enjson(301,'未找到付款好店',['url' =>'/pages/index']);
            }
        }
        return enjson(200,'成功',$store);
    }

     /**
     * 用户商家已领取的所有有效优惠券
     * @param integer $store_id
     * @param [type] $price
     * @return void
     */
    public function userCoupon(int $store_id = 0,$price){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['price']    = $this->request->param('price/f',0);
        $param['signkey']  = $this->request->param('signkey');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        //读取用户优惠券
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['is_end','=',0];                 //结束
        $condition[] = ['user_size','>',0];              //大小
        $condition[] = ['store_id','=',$store_id];       //好店
        $condition[] = ['uid','=',$this->user->id];      //用户
        if($param['price'] > 0){
            $condition[] = ['howmuch','<=',$param['price']]; //输入金额
        }
        $coupon  = CouponUser::where($condition)->field('id,name,size,user_size,tips,types,price,discount,weekday,create_time,ontypes')->select();
        if($coupon->isEmpty()){
            return enjson(204);
        }
        //判断是否可用
        foreach ($coupon as $val){
            if(strpos($val['weekday'],date('w')) && (($val['ontypes'] == 1 && strtotime(date('Y-m-d',$val['create_time']) . ' 23:59:59') < strtotime("now")) || $val['ontypes'] == 0)){
                $val['state'] = 0;
            }else{
                $val['state'] = 1;
            }
        }
        return enjson(200,'成功',$coupon);
    }

    /**
     * 读取管理商家和买单的优惠券
     **/
    public function Coupon(){
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['quan_id']  = $this->request->param('quan_id/d',0);
        $param['price']    = $this->request->param('price/f',0);
        $param['page']     = $this->request->param('page/d',1);
        $param['signkey']  = $this->request->param('signkey');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition   = [];
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_end','=',0];
        $condition[] = ['is_check','=',1];
        $condition[] = ['num','>',0];
        $condition[] = ['endtime','>',time()];
        if($param['price'] > 0){
            $condition[] = ['howmuch','<=',$param['price']]; //输入金额
        }
        //用户的优惠券
        $ids = CouponUser::userCouponIds($this->user->id);
        if (!empty($ids)) {
            $condition[] = ['id','notin',$ids];
        }
        //读取自己好店优惠券
        $store_coupon = [];
        if($param['store_id'] > 0 && $param['page'] == 1){
            $storeCoupon = Coupon::where($condition)->where('store_id','=',$param['store_id'])->field('id,name,size,tips,types,price,pay_price,discount,theme')->order('size desc,id desc')->select();
            if(!$storeCoupon->isEmpty()) {
                $store_coupon = $storeCoupon->toArray();
            }
        }
        $coupon = [];
        $condition[] = ['store_id','<>',$param['store_id']];
        if($param['quan_id']){
            $store = AllwinStore::where(['quan_id' => $param['quan_id']])->column('id');
            if(!empty($store)){
                $condition[] = ['store_id','in',$store];
            }
        }
        $rel = Coupon::where($condition)->field('id,name,size,tips,types,price,pay_price,discount,theme')->order('is_top desc,sort desc,size desc')->paginate(6,true);
        if (!$rel->isEmpty()) {
            $coupon = $rel->toArray()['data'];
        }
        if(!empty($store_coupon)){
            $coupon = array_merge_recursive($store_coupon,$coupon);
        }
        if(empty($coupon)){
            return enjson(204);
        }
        return enjson(200,'成功',$coupon);
    } 

 /**
     * 微信给商家支付
     * @param string $no
     * @return void
     */
    public function wechat(){
        if (request()->isPost()) {
            $rule = [
                'member_miniapp_id' => $this->miniapp_id,
                'store_id'          => $this->request->param('store_id/d'),
                'user_couponr_id'   => $this->request->param('user_couponr_id/d',0),
                'coupon_ids'        => $this->request->param('coupon_ids/a'),
                'money'             => $this->request->param('money/f'),
                'amount'            => $this->request->param('amount/f'),
                'code_id'           => $this->request->param('code_id/d'),
                'ucode'             => $this->request->param('ucode/s'),
                'uid'               => $this->user->id,
            ];
            $validate = $this->validate($rule, 'Dopay.gopay');
            if (true !== $validate) {
                return json(['code'=>403,'msg'=>$validate]);
            }
            //判断好店
            $store = AllwinStore::where(['member_miniapp_id' => $this->miniapp_id,'id' => $rule['store_id'],'is_lock' => 0])->field('id,name,state,manage_uid,mch_id')->find();
            if(empty($store)){
                return json(['code'=>403,'msg'=>'未找到好店']);
            }
            if(empty($store->manage_uid)){
                return json(['code'=>403,'msg'=>'未设置老板']);
            }
            if($store->state == 0){
                return json(['code'=>403,'msg'=>'好店未营业']);
            }
            //计算付款金额
            $amount = Order::countPrice($rule);
            if($amount['code'] == 403){
                return json($amount);
            }
            $amount = $amount['data'];
            //创建订单
            $order_no = $this->user->invite_code.order_no();
            //唤醒微信支付参数
            $payparm = [
                'openid'     => $this->user->miniapp_uid,
                'miniapp_id' => $this->miniapp_id,
                'name'       => $store->name,
                'order_no'   => $order_no,
                'total_fee'  => $amount['order_amount']*100,
                'notify_url' => api(4,'allwin/paymentnotify/index',$this->miniapp_id),
            ];
            //读取配置
            $setting = AllwinConfig::getConfig($this->miniapp_id);
            if($setting->is_psp == 1){ //服务商模式
                if($store->mch_id){
                    $default_mchid = MchId::getMch($store->mch_id);   //商户的商户号
                }else{
                    $default_mchid = MchId::getMch(0, $this->miniapp_id);  //默认收款账户
                }
                if (empty($default_mchid)) {
                    return json(['code'=>403,'msg'=>'未找到商户号']);
                }
                $payparm['mchid'] = $default_mchid->mchid;
                //分账参数
                switch ($setting->is_fees_types){
                    case 1:
                        if($rule['user_couponr_id']){
                            $payparm['profit_sharing'] = $setting->is_wechat_profitsharing == 1 || $payparm['profit_sharing'] ? 'Y' : 'N';
                        }else{
                            $payparm['profit_sharing'] = 'N';
                        }
                        break;
                    case 2:
                        $payparm['profit_sharing'] = 'N';
                        break;
                    default:
                        $payparm['profit_sharing'] = $setting->is_wechat_profitsharing == 1 ? 'Y' : 'N';
                        break;
                }
            }
            $ispay = WechatPay::orderPay($payparm);
            if($ispay['code'] == 0){
                return json(['code'=>403,'msg'=>$ispay['msg']]);
            }
            //添加订单记录
            $rule['order_no']        = $order_no;
            $rule['coupon_price']    = $amount['coupon_user_price'];  //优惠金额
            $rule['store_amount']    = $amount['store_amount'];       //好店应收
            $rule['platform_amount'] = $amount['platform_amount'];    //领优惠券金额
            $rule['order_amount']    = $amount['order_amount'];       //实支付金额
            $rule['user_amount']     = $amount['user_amount'];        //输入金额
            $rel = Order::addOrder($rule);
            if(!$rel){
                return json(['code'=>403,'msg'=>'订单创建失败']);
            }
            //把支付packageID添加到数据库
            $package = $ispay['data']['package'];
            SystemMemberForm::addForm($this->miniapp_id,$this->user->id,substr($package,10));
            $ispay['data']['url'] = '/pages/store/views?store_id='.$rule['store_id'];
            return enjson(200,'成功',$ispay['data']); 
        }
    }
}